package member;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import book.BookBean;
import book.ReserveBean;

import common.DBManager;
import common.TableManager;

public class ReserveListServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");

		// ページ設定
		String pageStr = request.getParameter("page");
		int page;
		int max = 10;	// 1ページあたりの表示件数
		if(pageStr == null) {
			page = 1;
		} else {
			page = Integer.parseInt(pageStr);
		}
		int start = (page - 1) * max;

		// 利用者情報取得SQL文
		String sql = "select * from reserves order by id limit " + start + ", " + max;

		// 利用者件数取得SQL文
		String sqlCnt = "select count(*) as cnt from reserves";

		Connection con = null;
		Statement smt = null;

		try {
			con = DBManager.getConnection();
			smt = con.createStatement();
			ResultSet rs = smt.executeQuery(sql);

			List<ReserveBean> list = new ArrayList<ReserveBean>();
			List<BookBean> listAppend = new ArrayList<BookBean>();
			List<MemberBean> listAppend2 = new ArrayList<MemberBean>();

			while(rs.next()) {

			ReserveBean reserves = (ReserveBean)TableManager.getRecord(TableManager.RESERVES_TABLE,rs.getInt("ID")).getBean();
			BookBean books=reserves.getBookBean();
			MemberBean members=reserves.getMemberBean();

			list.add(reserves);
			listAppend.add(books);
			listAppend2.add(members);

			}
			request.setAttribute("list", list);
			request.setAttribute("listAppend", listAppend);
			request.setAttribute("listAppend2", listAppend2);

			rs = smt.executeQuery(sqlCnt);
			rs.next();
			Integer cnt = new Integer(rs.getInt("cnt"));
			request.setAttribute("cnt", cnt);

		}catch(NullPointerException e) {
			e.printStackTrace();
			request.setAttribute("list", null);
		}
		catch(SQLException e) {
			throw new ServletException(e);
		} finally {
			if(smt != null) {
				try {
					smt.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			if(con != null) {
				try {
					con.close();
				} catch(SQLException ignore) {
					// none
				}
			}
		}
		request.setAttribute("page", page);
		request.getRequestDispatcher("/member/userMemberReserve.jsp").forward(request, response);

	}


}
